<script setup lang="ts">
import { onBeforeMount, onMounted, ref } from 'vue'
import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core'
import UniverPresetSheetsCoreZhCN from '@univerjs/preset-sheets-core/locales/zh-CN'
import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets'
import { DEFAULT_WORKBOOK_DATA } from './data'
import '@univerjs/preset-sheets-core/lib/index.css'
import UniverPresetSheetsAdvancedZhCN from '@univerjs/preset-sheets-advanced/locales/zh-CN'
import UniverPresetSheetsDrawingZhCN from '@univerjs/preset-sheets-drawing/locales/zh-CN'

const univerInstace = ref()
const workbook = ref();
const container = ref<HTMLElement | null>(null);
const univerAPIInstace = ref()
const data = ref(DEFAULT_WORKBOOK_DATA)
const json = localStorage.getItem('sheet-data')
const ranges = ref()
if (json !== 'undefined' && json !== null) {
  data.value = JSON.parse(json as string)
}
async function init() {
  const { univer, univerAPI } = createUniver({
    locale: LocaleType.ZH_CN,
    locales: {
      [LocaleType.ZH_CN]: mergeLocales(
        UniverPresetSheetsCoreZhCN,
        UniverPresetSheetsDrawingZhCN,
        UniverPresetSheetsAdvancedZhCN,
      ),
    },
    presets: [
      UniverSheetsCorePreset({
        container: container.value!,
      }),
    ],
  })
  univerInstace.value = univer
  univerAPIInstace.value = univerAPI
  workbook.value = univerAPI.createWorkbook(data.value)

  univerAPI.onBeforeCommandExecute(async (command) => {
    const { id, type, params } = command
    // 在命令执行前执行自定义逻辑
    if (id == 'sheet.operation.set-activate-cell-edit') {
      // @ts-ignore
      ranges.value = command.params!.primary;
    }
  })
}


async function saveWorkbook() {
  if (!workbook.value) {
    throw new Error('Workbook is not initialized');
  }
  return workbook.value.save();
}

onMounted(() => {
  init()

})

onBeforeMount(() => {
  univerInstace.value?.destroy()
})

defineExpose({
  saveWorkbook,
});
</script>

<template>
  <div ref="container" class="univer-container"></div>
  {{ ranges }}
</template>

<style scoped>
.read-the-docs {
  color: #888;
}

.univer-container {
  width: 100%;
  height: 100vh;
}
</style>
